package com.frxuexi.lib_base.base

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.DatePicker
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.TimePicker
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.frxuexi.lib_base.R
import java.lang.reflect.ParameterizedType
import java.util.Calendar
import kotlin.math.min

abstract class BaseActivity<VDB:ViewDataBinding,VM:BaseViewModel>:AppCompatActivity() {
    //取出泛型参数列表
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    val binding by lazy {
        val clazz=type[0] as Class<VDB>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        method.invoke(null,layoutInflater) as VDB
    }


    val vm by lazy {
        val clazz=type[1] as Class<VM>
       ViewModelProvider(this).get(clazz)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initView()
        initData()
    }

    abstract fun initData()

    abstract fun initView()

    fun showDateDialog(et:EditText){
        val calendar = Calendar.getInstance()
        DatePickerDialog(this,object :DatePickerDialog.OnDateSetListener{
            override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
                val mon=if(month+1<10) "0"+(month+1) else month+1
                val day=if(dayOfMonth<10) "0"+dayOfMonth else dayOfMonth
                et.setText("${year}-${mon}-${day}")
            }
        },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show()
    }

    fun showTimeDialog(et:EditText){
        val calendar = Calendar.getInstance()
        TimePickerDialog(this,object :OnTimeSetListener{
            override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
                val h=if(hourOfDay<10) "0"+hourOfDay else hourOfDay
                val m=if(minute<10) "0"+ minute else minute
                et.setText("${h}:${m}:00")
            }
        },calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show()
    }
}